import FormFilter from '@/components/ManageFormFilter/FormFilter';
import MonitorlevlDrawer from '@/components/MonitorManage/monitorlevlDrawer';
import MonitorModal from '@/components/MonitorManage/monitorModal';
import DetectorManager from '@/components/MonitorManage/detectorView'
import SliderSelect from '@/components/MonitorManage/SliderSelect';
import { CheckOutlined, CloseOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { PageHeaderWrapper, ProFormDigitRange } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Col,
  Descriptions,
  Divider,
  Drawer,
  Form,
  message,
  Popconfirm,
  Row,
  Slider,
  Switch,
  Table,
} from 'antd';
import React, { Component } from 'react';
import { connect } from 'umi';

const DescriptionItem = ({ title, content }) => (
  <div className="site-description-item-profile-wrapper">
    <p className="site-description-item-profile-p-label">{title}:</p>
    {content}
  </div>
);

//断面监测管理界面
class MonitorManager extends Component {
  state = {
    drawerVisible: false,
  };
  componentDidMount() {
    // 当页面组件完全的加载完毕触发此生命周期，只会触发一次
    this.formRef = React.createRef();
    this.modalRef = React.createRef();
    this.tableRef = React.createRef();
    //初始数据加载
    this.handleRefreshData();
  }

  //请求设备器table表数据
  handleRefreshData() {
    let formData = {};
    try {
      const getFormData = this.formRef.current.getFieldsValue();
      formData = { ...getFormData };
    } catch (e) {
      formData = undefined;
    }

    // 获取表格数据
    const { dispatch } = this.props;

    dispatch({
      type: 'monitorManage/changeLoadingStatus',
    });
    if (dispatch) {
      dispatch({
        type: 'monitorManage/getData',
        payload: formData ? { formData } : {},
      });
    }
  }

  //重置查询表单
  resetAllFields() {
    const { current } = this.formRef;
    current.resetFields();
  }

  //查看监测设备
  detectorView(type, deviceId) {
    let detectorData = { type, deviceId };
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/getDetectorData',
        payload: { detectorData },
      });
  }

  //新增/修改Model
  changeModal(type = 'add', data = {}) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/changeModalVisibleAndSetValue',
        payload:
          type === 'update'
            ? {
              type,
              data,
            }
            : {
              type,
            },
      });
  }

  changePage(currentPage) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/changePage',
        payload: currentPage,
      }).then(() => {
        this.handleRefreshData();
      });
  }

  submitMonitorInfo(type = 'add', values) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/submitMonitorInfo',
        payload: {
          type,
          formData: {
            ...values,
            // address: values.address.join('/'),
          },
        },
        callback: (res) => {
          if (res.code == 200) {
            message.success(`${type === 'add' ? '添加' : '修改'}成功`);
            this.handleCancel();
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  //关闭modal窗
  handleCancel() {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/changeModelVisibleAndCloseModel',
      });
  }

  // //改变Drawer状态并保存行记录
  // changeDrawerStatusAndSaveRecord(record) {
  //   const { dispatch } = this.props;
  //   dispatch &&
  //     dispatch({
  //       type: 'monitorManage/changeDrawerStatus',
  //       payload: record,
  //     });
  // }

  deleteMonitorById(record) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/deleteMonitorInfo',
        payload: record,
        callback: (res) => {
          if (res.code == 200) {
            message.success(`删除成功`);
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  UpdateMonitorInfo(record) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/updateMonitorInfo',
        payload: record,
        callback: (res) => {
          if (res.code == 200) {
            message.success(`修改成功`);
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  openDrawerAndSetDetail(record) {
    //打开污染物等级划定设置界面
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'monitorManage/changeMonitorlevlDrawer',
        payload: record,
      });
  }

  render() {
    const {
      makers,
      loading,
      selectedRowsKeys = [],
      dispatch,
      visible,
      modalVisible,
      optiontype,
      makerDetail,
      effectPageInfo,
      pagination,
    } = this.props;
    const { drawerVisible } = this.state;
    const formName = '断面信息筛选';
    const tableName = '断面列表';

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        showFilter: false,
        align: 'center',
        render: (value, record, index) => {
          return `${(effectPageInfo.current - 1) * pagination.size + index + 1}`;
        },
      },
      {
        title: '断面编号',
        dataIndex: 'markerId',
        showFilter: true,
        align: 'center',
      },
      {
        title: '断面名称',
        dataIndex: 'markerName',
        showFilter: true,
        align: 'center',
        align: 'center',
      },

      {
        title: '所在位置',
        dataIndex: 'address',
        showFilter: false,
        align: 'center',
      },
      {
        title: '经度',
        dataIndex: 'longitude',
        showFilter: false,
        align: 'center',
      },
      {
        title: '维度',
        dataIndex: 'latitude',
        showFilter: false,
        align: 'center',
      },
      // {
      //   title: '创建人',
      //   dataIndex: 'username',
      //   align: 'center',
      //   showFilter: true,
      // },
      // {
      //   title: '创建日期',
      //   dataIndex: 'createTime',
      //   align: 'center',
      //   showFilter: false,
      // },
      {
        title: '是否监测',
        dataIndex: 'state',
        showFilter: true,
        checkbox: true,
        defaultValue: [0, 1],
        align: 'center',
        Option: [
          { value: 0, label: '是' },
          { value: 1, label: '否' },
        ],
        render: (value, record) => {
          return (
            <Switch
              checkedChildren={<CheckOutlined />}
              unCheckedChildren={<CloseOutlined />}
              defaultChecked={value == 0 ? true : false}
              onChange={(value) => {
                const newRecord = { ...record, state: value ? 0 : 1 };
                this.UpdateMonitorInfo(newRecord);
              }}
            />
          );
        },
      },

      {
        title: '操作',
        dataIndex: '',
        align: 'center',
        width: 250,
        render: (text, record, index) => {
          return (
            <div>
              <Button
                type={'default'}
                size={'small'}
                style={{ marginRight: 5 }}
                onClick={() => {
                  this.detectorView('open', record.deviceId);
                }}
              >
                查看监测器
              </Button>
              <Button
                type={'primary'}
                size={'small'}
                style={{ marginRight: 5 }}
                onClick={() => {
                  this.changeModal('update', record);
                }}
              >
                修改
              </Button>
              <Popconfirm
                title="确定删除此断面?"
                onConfirm={() => {
                  this.deleteMonitorById(record);
                }}
              >
                <Button type={'primary'} danger size={'small'}>
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return (
      <PageHeaderWrapper>
        <Row>
          <Col span={24}>
            <Card title={formName} bordered={false} style={{ marginBottom: 20 }}>
              <Row>
                <Form
                  layout="inline"
                  ref={this.formRef}
                  onFinish={(values) => {
                    this.handleRefreshData();
                  }}
                  style={{ marginBottom: 20 }}
                >
                  <FormFilter columns={columns} />
                  <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
                    查询
                  </Button>
                  <Button
                    type="primary"
                    htmlType="button"
                    onClick={() => {
                      this.resetAllFields();
                    }}
                  >
                    重置
                  </Button>
                </Form>
              </Row>
              <Row>
                <Button
                  type="primary"
                  htmlType="button"
                  style={{ marginRight: 20 }}
                  onClick={() => {
                    this.changeModal();
                  }}
                >
                  <PlusCircleOutlined />
                  新增监测断面
                </Button>
                <Button type="primary" htmlType="button" danger>
                  <DeleteOutlined />
                  批量删除
                </Button>
              </Row>
            </Card>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Card bordered={false}>
              <Table
                rowKey={'id'}
                dataSource={makers}
                loading={loading}
                columns={columns}
                rowSelection={[]}
                ref={this.tableRef}
                scroll={{ x: 'max-content' }}
                size={'small'}
                pagination={{
                  showQuickJumper: false,
                  showTotal: () => `共${pagination.total}条`,
                  pageSize: pagination.size,
                  total: pagination.total, //数据的总的条数
                  onChange: (current) => this.changePage(current), //点击当前页码
                }}
              />
            </Card>
          </Col>
        </Row>
        <MonitorModal
          visible={modalVisible}
          optiontype={optiontype}
          makerDetail={makerDetail}
          ref={this.modalRef}
          handleSumbit={(type, values) => {
            this.submitMonitorInfo(type, values);
          }}
          centered
        />
        <DetectorManager
          visible={visible}
        />

        <MonitorlevlDrawer
          handleRefreshData={() => {
            this.handleRefreshData();
          }}
        />
      </PageHeaderWrapper>
    );
  }
}

export default connect(({ monitorManage, detectorManage }) => ({
  makers: monitorManage.makers,
  loading: monitorManage.loading,
  pagination: monitorManage.pagination,
  selectedRowsKeys: monitorManage.selectedRowsKeys,
  modalVisible: monitorManage.modalVisible,
  visible: detectorManage.visible,
  optiontype: monitorManage.optiontype,
  effectPageInfo: monitorManage.effectPageInfo,
  makerDetail: monitorManage.makerDetail,
}))(MonitorManager);
